import { list as dictList } from "@/api/dict";

const utilsFunc = {

  //字典信息获取
  getDictList(type, callback, errCallback) {
    let params = new URLSearchParams();
    params.append("dictType", type);
    return dictList(params)
      .then((res) => {
        // console.log(type + "字典--", res);
        if (res.type == "success") {
          if (callback) {
            callback(res.data);
          }
        }
      })
      .catch((err) => {
        if (errCallback) {
          errCallback();
        }
      });
  },

  // 回显数据字典
  selectDictLabel(datas, value) {
    var actions = [];
    if(this.isNull(datas)){
      return value;
    }else{
      Object.keys(datas).some((key) => {
        if (datas[key].id == ('' + value)) {
          actions.push(datas[key].name);
          return true;
        }
      })
      return actions.join('');
    }
  },

  // 创建全局唯一标识符
  getUUID() {
    var d = new Date().getTime()
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = (d + Math.random() * 16) % 16 | 0
      d = Math.floor(d / 16)
      return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
    })
    return uuid
  },
  // 判空
  isNull(value) {
    if (typeof (value) !== 'boolean') {
      if (value == null || value == 'null' || value == undefined || value === '' || value == 'undefined') 
      {
        return true
      } else {
        return false
      }
    } else {
      return value
    }
  },

  /**
   * @param {string} id,{array} list
   * @returns {obj}
   * 根据id查找树节点，传入父节点id 返回的即是该父节点对象。
   */
  findTree(id, treeList) {
    for (var i in treeList) {
      // 如果没找到，就把下级再递归进来
      if (id == treeList[i].id) {
        return treeList[i]
      } else {
        const n = this.findTree(id, treeList[i].childrens)
        // 有下级才返回
        if (n != null) {
          return n
        }
      }
    }
    return null
  },

  /**
   * @param treeList,
   * @returns [id] id数组
   * 为选择结点,过滤父结点。
   */
  cleanTree(treeList, selectList) {
    const _this = this
    var result = []
    treeList.forEach(function (node) {
      if (node.childrens.length > 0) {
        const arr = _this.cleanTree(node.childrens, selectList)
        arr.forEach(function (s) {
          result.push(s)
        })
      } else {
        // 没有子结点，去查找是否选中
        selectList.forEach(function (n) {
          if (n.id == node.id) {
            result.push(n.id)
          }
        })
      }
    })
    return result
  },

  /**
   * @param int areaId,
   * @returns obj 省市区id对象
   * 根据区id组出市id，省di
   */
  decodeArea(areaId) {
    var result = {
      province: 0,
      city: 0,
      area: 0
    }
    var resultName = {
      province: '',
      city: '',
      area: ''
    }
    result.area = areaId
    result.city = result.area.substring(0, result.area.length - 2) + '00'
    result.province = result.area.substring(0, result.area.length - 4) + '0000'
    result.area = parseInt(result.area)
    result.city = parseInt(result.city)
    result.province = parseInt(result.province)
    let provinceAllObj = {}
    let provinceObj = {}
    let cityObj = {}
    for (const i in DISTRICTS) {
      if (i == 100000) {
        provinceAllObj = DISTRICTS[i]
        for (const p in provinceAllObj) {
          if (p == result.province) {
            resultName.province = provinceAllObj[p]
          }
        }
      }
    }
    for (const i in DISTRICTS) {
      if (i == result.province) {
        provinceObj = DISTRICTS[i]
        for (const p in provinceObj) {
          if (p == result.city) {
            resultName.city = provinceObj[p]
          }
        }
      }
    }
    for (const i in DISTRICTS) {
      if (i == result.city) {
        cityObj = DISTRICTS[i]
        console.log(cityObj)
        for (const c in cityObj) {
          console.log(result.area)
          if (c == result.area) {
            resultName.area = cityObj[c]
          }
        }
      }
    }
    console.log(resultName)
    return resultName
  },
  beforeMount() {
    var curHeight = null
    window.onresize = () => {
      return (() => {
        var h = document.documentElement.clientHeight || document.body.clientHeight
        curHeight = h - 296// 减去页面上固定高度height
        console.log(h)
      })()
    }
    return curHeight
  },
  thumbnail(url, w, h) {
    if (this.isNull(url)) {
      return ''
    }
    if (url.indexOf('?x-oss-') != -1) {
      url = url.substring(0, url.indexOf('?x-oss-'));
    }
    h = Math.round(h)
    w = Math.round(w)
    if (url.substring(0, 11) == 'http://cdnx') {
      return url + '?x-oss-process=image/resize,m_fill,w_' + w + ',h_' + h + '/quality,q_90'
    } else if (url.substring(0, 10) == 'http://cdn') {
      return url + '@' + w + 'w_' + h + 'h_1e_1c_100Q'
    } else {
      return url
    }
  },
  // 获取主机
  host() {
    var url = window.location.href
    var len = url.indexOf('//')
    var http = url.substring(0, len)

    return http + '//' + window.location.host
  },

  mapToUrl(data) {
    if (this.isNull(data)) {
      return ''
    }
    var _result = []
    for (var key in data) {
      var value = data[key]
      if (value === null) {
        return ''
      }
      if (value.constructor == Array) {
        value.forEach(function (_value) {
          _result.push(key + '=' + _value)
        })
      } else {
        _result.push(key + '=' + value)
      }
    }
    const url = _result.join('&')
    if (!this.isNull(url) && url.length > 0) {
      return '?' + url
    } else {
      return ''
    }
  },

  base64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
      .replace(/\-/g, '+')
      .replace(/_/g, '/');

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  },

  arrayBufferToBase64(buffer) {
    var binary = '';
    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  },
  isMobile() {
    let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    return flag;
  },
  dateFormatter(date) {
    if (date==null) {
      return null;
    }
    date = new Date(date)
    let fmt = "YYYY-mm-dd"
    let ret;
    const opt = {
      "Y+": date.getFullYear().toString(),        // 年
      "m+": (date.getMonth() + 1).toString(),     // 月
      "d+": date.getDate().toString()            // 日
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
    };
    return fmt;
  }

}

export default utilsFunc
